package com.example.multiple.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.Executor;

/**
 * @Author yanggld
 * @Date 2019/9/27-17:31
 * @Description
 * 配置修改的监听事件
 */
@Component
public class NacosConfig implements ApplicationContextAware {

	private String dataId = "multipledatasource.properties";

	private String group = "DEFAULT_GROUP";

	@Value("${spring.cloud.nacos.config.server-addr}")
	private String serverAddr;

	@Value("${spring.cloud.nacos.config.namespace}")
	private String namespace;

	private ApplicationContext applicationContext;



	@PostConstruct
	public void dynamicRouteByNacosListener() {
		try {
			Properties properties = new Properties();
			properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
			properties.put(PropertyKeyConst.NAMESPACE, namespace);
			ConfigService configService = NacosFactory.createConfigService(properties);
			configService.getConfig(dataId, group, 5000);
			configService.addListener(dataId, group, new Listener() {
				@Override
				public void receiveConfigInfo(String configInfo) {
				}
				@Override
				public Executor getExecutor() {
					return null;
				}
			});

//			boolean isPublishOk = configService.publishConfig(dataId, group, "content");
//			System.out.println(isPublishOk);
//
//			content = configService.getConfig(dataId, group, 5000);
//			System.out.println(content);
//
//			boolean isRemoveOk = configService.removeConfig(dataId, group);
//			System.out.println(isRemoveOk);
//
//			content = configService.getConfig(dataId, group, 5000);
//			System.out.println(content);

		} catch (Exception e) {
			e.printStackTrace();
		}



	}


	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
